package com.lone.smallmovie.controller;

import com.alibaba.fastjson.JSONObject;
import com.lone.smallmovie.model.User;
import com.lone.smallmovie.model.result.UserResult;
import com.lone.smallmovie.service.impl.UserServiceImpl;
import com.lone.smallmovie.utils.AES;
import com.lone.smallmovie.utils.LoginSession;
import com.lone.smallmovie.utils.MapResultUtils;
import com.lone.smallmovie.utils.UUIDUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    private Logger log = Logger.getLogger(UserController.class);

    @Autowired
    private UserServiceImpl userService;


    @RequestMapping(value = "/registered", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> registered(HttpServletRequest request, Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        String mUserAccount = request.getParameter("userAccount");
        String mPassword = request.getParameter("password");
//        String mSmsCode = request.getParameter("smsCode");
        log.info("注册    用户名 ：" + mUserAccount + "\n" + "密码 :" + mPassword);
        if (mUserAccount == null || mUserAccount == "" || mPassword == null || mPassword == "") {
            return MapResultUtils.parameterError();
        }
        User user = userService.queryUserByUserAccount(mUserAccount);
        if (user != null) {
            map.put("status", "2");
            map.put("message", "该账号已被注册！");
            return map;
        } else {
            int mResult = userService.registered(UUIDUtils.getUUID(), mUserAccount, mPassword);
            if (mResult == 1) {
                map.put("status", "0");
                map.put("message", "恭喜你注册成功！");
                log.info("用户 " + mUserAccount + "注册账户----- 成功");

            } else {
                map.put("status", "1");
                map.put("message", "注册失败！");
                log.info("用户 " + mUserAccount + "注册账户----- 失败");
            }
            return map;


        }

    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request, Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        String mUserAccount = request.getParameter("userAccount");
        String mPassword = request.getParameter("password");
        log.info("用户名 ：" + mUserAccount + "\n" + "密码 :" + mPassword);
        if (mUserAccount == null || mUserAccount == "" || mPassword == null || mPassword == "") {
            return MapResultUtils.parameterError();
        }
        User user = userService.login(mUserAccount, mPassword);

        if (user == null) {
            map.put("status", "1");
            map.put("message", "密码不正确!");
            log.info("==========================登陆失败==================");
        } else {
            model.addAttribute(user);
            UserResult resultUser = new UserResult();
            resultUser.setId(user.getId());
            resultUser.setUid(user.getUser_id());
            resultUser.setAccount(user.getUser_account());
            resultUser.setNickName(user.getUser_name());
            resultUser.setAge(user.getUser_age());
            resultUser.setHeadPortraitUrl(user.getUser_headurl());


            Map<String, String> sessionMap = new HashMap<String, String>();
            sessionMap.put("userId", String.valueOf(user.getId()));
            sessionMap.put("userLoginUUID", UUIDUtils.getUUID());

            JSONObject jsObj = new JSONObject();
            jsObj.put("userId", sessionMap.get("userId"));
            jsObj.put("userLoginUUID", sessionMap.get("userLoginUUID"));

            String token = AES.AES_en(jsObj.toString(), AES.AES_KEY);

            sessionMap.put("token", token);

            resultUser.setToken(token);
            request.getSession().setAttribute("user", sessionMap);
            LoginSession.addMap(String.valueOf(user.getId()), sessionMap);

            log.info("用户 token  =  " + token);

            map.put("status", "0");
            map.put("message", "登陆成功!");
            map.put("userInfo", resultUser);
            log.info("用户 " + mUserAccount + "登录成功----- ");

        }

        return map;
    }

    @RequestMapping(value = "/updateNickName", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateNickName(HttpServletRequest request, Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        String userAccount = request.getParameter("userAccount");
        String nickName = request.getParameter("nickName");
        if (userAccount == null || userAccount == "" || nickName == null || nickName == "") {
            map.put("status", "-1");
            map.put("message", "传入参数不合法!");
            return map;
        }
        int result = userService.updateNickName(nickName, userAccount);
        if (result == 1) {
            map.put("status", "0");
            map.put("message", "昵称修改成功!");
            log.info("用户 " + userAccount + "修改昵称---------- 成功");

        } else {
            map.put("status", "1");
            map.put("message", "昵称修改失败!");
        }
        return map;


    }

    @RequestMapping(value = "/changeLoginPassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> changePassword(HttpServletRequest request, Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        String mUserAccount = request.getParameter("userAccount");
        String mOldPassword = request.getParameter("oldPassword");
        String mNewPassword = request.getParameter("newPassword");
        if (mUserAccount == null || mUserAccount == "" || mOldPassword == null || mOldPassword == ""
                || mNewPassword == null || mNewPassword == "") {
            return MapResultUtils.parameterError();
        }
        User user = userService.login(mUserAccount, mOldPassword);
        if (user == null) {
            map.put("status", "1");
            map.put("message", "旧密码不正确!");
        } else {
            if (mOldPassword.equals(mNewPassword)) {
                map.put("status", "5");
                map.put("message", "新的登录密码不能和旧密码一致!");
                return map;
            }
            int result = userService.changeLoginPasswordByUserAccount(mUserAccount, mNewPassword);
            if (result == 1) {
                log.info("用户 "+mUserAccount+"修改密码----------成功 ");
                map.put("status", "0");
                map.put("message", "登录密码修改成功!");
            } else {
                map.put("status", "1");
                map.put("message", "登录密码修改失败!");
            }


        }
        return map;
    }
}
